package com.rybbaby.tss.front.tssCourse.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.rybbaby.tss.core.annotation.RequestLog;
import com.rybbaby.tss.core.annotation.Token;
import com.rybbaby.tss.core.annotation.validator.RegexpValidator;
import com.rybbaby.tss.core.annotation.validator.StringValidator;
import com.rybbaby.tss.core.bean.PageBean;
import com.rybbaby.tss.core.consts.RoleConsts;
import com.rybbaby.tss.core.hqlsearch.HqlGenerateUtil;
import com.rybbaby.tss.core.utils.AjaxJsonResponse;
import com.rybbaby.tss.core.utils.PropertiesReadUtil;
import com.rybbaby.tss.core.utils.SequenceUtil;
import com.rybbaby.tss.core.utils.StringUtils;
import com.rybbaby.tss.core.web.controller.BaseController;
import com.rybbaby.tss.front.tssCourse.entity.TssCourse;
import com.rybbaby.tss.front.tssCourse.service.ITssCourseService;
import com.rybbaby.tss.platform.sysAdminUser.entity.SysAdminUser;
import com.rybbaby.tss.platform.sysAdminUser.service.ISysAdminUserService;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.io.Serializable;
import java.util.List;
import java.util.Map;

/**
 * @author 雷春琼
 * @description 课程表管理
 * @createDate 2017-08-10 下午7:57:36
 */
@Controller
@RequestMapping(value = "tssCourseController")
public class TssCourseController extends BaseController {

    @Autowired
    private ITssCourseService tssCourseService;
    @Autowired
    private ISysAdminUserService sysAdminUserService;

    /**
     * 获取课程表列表
     *
     * @return
     * @throws IOException
     */
    @RequestLog(content = "获取课程表列表", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "tssCourseList", method = RequestMethod.POST)
    public ModelAndView tssCourseList(TssCourse entity, PageBean paramPageBean, @RequestParam(required = true) Integer type) {
        ModelAndView mav = null;
        try {
            if (type == 1) {
                //亲子课程设置
                mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssCourseListView"));
            } else if (type == 2) {
                //过渡课程设置
                mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssTransitCourseListView"));
            }
            Map<String, String[]> unLockMap = getParameterMap(request);
            DetachedCriteria dc = DetachedCriteria.forClass(TssCourse.class);
            HqlGenerateUtil.fillDetachedCriteria(dc, entity, unLockMap);
            String ids = "";
            //获取当前登录者
            String adminUserId = super.getLoginUser().getId();
            SysAdminUser sysAdminUser = this.sysAdminUserService.get(adminUserId);
            //获取当前登录者所拥有角色
            List<String> roleList = super.getLoginAdminRoles();

            if (roleList.contains(RoleConsts.TSS_COUNSELOR) || roleList.contains(RoleConsts.TSS_TEACHER)) {
                dc.add(Restrictions.sqlRestriction(" adminUserId in ('" + adminUserId + "') "));
            } else {
                List<String> idsList = super.getUserIdByRoleAndSchololId(sysAdminUser.getSchoolId());
                ids = StringUtils.join(idsList, "','");
                dc.add(Restrictions.sqlRestriction(" adminUserId in ('" + ids + "') "));
            }
            dc.add(Restrictions.eq("type", type));
            dc.addOrder(Order.desc("updateTime"));
            PageBean pageBean = tssCourseService.pageList(dc, paramPageBean.getPageNo(), paramPageBean.getPageSize());
            mav.addObject(super.SEARCH_MAP, unLockMap);
            mav.addObject(super.PAGE_BEAN, pageBean);
            mav.addObject("courseType", type);
            mav.addObject("searchFormId", SEARCH_FORM);
            mav.addObject("actionUrl", request.getRequestURI());
            mav.addObject("pagingBar", pageBean.getPagingBar(SEARCH_FORM));
            mav.addObject("serializeNum", SequenceUtil.getUpperCaseUUID());
            String requestURI = StringUtils.substringBeforeLast(request.getRequestURI(), "/");
            mav.addObject("editUrl", requestURI + "/toEditView.do");
            mav.addObject("deleteUrl", requestURI + "/delete.do");
            mav.addObject("batchDeleteUrl", requestURI + "/batchDelete.do");
        } catch (Exception e) {
            throw e;
        }
        return mav;
    }

    /**
     * 转到编辑视图
     *
     * @param targetDateId       接收编辑参数的临时对象
     * @param serializeNum 请求标识
     * @return
     */
    @RequestLog(content = "转到课程表视图", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "toEditView", method = RequestMethod.GET)
    public ModelAndView toEditView(@RequestParam(required = true) String targetDateId, @RequestParam(required = true) String serializeNum, @RequestParam(required = true) String courseType) {
        ModelAndView mav = null;
        Integer type = Integer.valueOf(courseType);
        if (type == 1) {
            mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssCourseEditView"));
        } else if (type == 2) {
            mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssTransitCourseEditView"));
        }
        if (StringUtils.isNotBlank(targetDateId)) {
            TssCourse editEntity = this.tssCourseService.get(targetDateId);
            mav.addObject("editEntity", editEntity);
            mav.addObject("editModel", "edit");
        } else {
            mav.addObject("editModel", "add");
        }
        mav.addObject("serializeNum", serializeNum);
        mav.addObject("saveUrl", StringUtils.substringBeforeLast(request.getRequestURI(), "/") + "/saveOrUpdate.do");
        return mav;
    }

    /**
     * 保存编辑的对象
     *
     * @param entity 被编辑对象
     * @return
     */
    @ResponseBody
    @RequestLog(content = "保存课程表对象", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "saveOrUpdate", method = RequestMethod.POST)
    public String saveOrUpdate(TssCourse entity) {
        AjaxJsonResponse ajr = new AjaxJsonResponse();
        try {
            String id = entity.getId();
            ajr.setResMsg("保存成功!");
            if (StringUtils.isNotBlank(id)) {
                TssCourse destEntity = this.tssCourseService.get(id);
                BeanUtils.copyProperties(entity, destEntity, "createTime", "updateTime");
                destEntity.setUpdateTime(new java.sql.Timestamp(System.currentTimeMillis()));
                destEntity.setAdminUserId(super.getLoginUser().getId());
                this.tssCourseService.updateEntitiy(destEntity);
            } else {
                entity.setAdminUserId(super.getLoginUser().getId());
                entity.setCreateTime(new java.sql.Timestamp(System.currentTimeMillis()));
                entity.setUpdateTime(new java.sql.Timestamp(System.currentTimeMillis()));
                Serializable newId = this.tssCourseService.save(entity);
                if (newId == null) {
                    ajr.setResCode(301);
                    ajr.setResMsg("保存失败!");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            ajr.setResCode(500);
            ajr.setResMsg("保存失败(" + e.getMessage() + ")!");
        }
        return ajr.jsonResponse(false);
    }

    /**
     * 删除指定id的对象
     *
     * @param id 需要被删除的对象id
     * @return
     */
    @ResponseBody
    @RequestLog(content = "删除属性", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "delete", method = RequestMethod.GET)
    public String delete(@StringValidator(nullable = false) String id) {
        AjaxJsonResponse ajr = new AjaxJsonResponse();
        try {
            ajr.setResMsg("删除成功!");
            if (StringUtils.isNotBlank(id)) {
                this.tssCourseService.deleteEntityById(id);
            } else {
                ajr.setResMsg("删除失败!");
                ajr.setResCode(302);
            }
        } catch (Exception e) {
            e.printStackTrace();
            ajr.setResCode(500);
            ajr.setResMsg("删除失败(" + e.getMessage() + ")!");
        }
        return ajr.jsonResponse(false);
    }

    /**
     * 批量删除指定id的对象
     *
     * @param ids 需要被删除的对象id组成的字符串
     * @return
     */
    @ResponseBody
    @RequestLog(content = "删除属性", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "batchDelete", method = RequestMethod.GET)
    public String batchDelete(@RegexpValidator(nullable = false, regexp = "^(\\w+,?)+\\w+$") String ids) {
        AjaxJsonResponse ajr = new AjaxJsonResponse();
        try {
            ajr.setResMsg("删除成功!");
            if (StringUtils.isNotBlank(ids)) {
                boolean batchDelete = this.tssCourseService.batchDelete(ids.split(","));
                if (!batchDelete) {
                    ajr.setResMsg("删除失败!");
                    ajr.setResCode(302);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            ajr.setResCode(500);
            ajr.setResMsg("删除失败(" + e.getMessage() + ")!");
        }
        return ajr.jsonResponse(false);
    }

    /**
     * 根据状态课程员工信息
     *
     * @param targetDateId
     * @param isBlockUp
     * @return
     */
    @ResponseBody
    @RequestLog(content = "根据状态修改课程信息", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "updateCourseByIsBlockUp", method = RequestMethod.POST)
    public String updateStaffByIsBlockUp(@RequestParam(required = true) String targetDateId, @RequestParam(required = true) Boolean isBlockUp) {
        AjaxJsonResponse ajr = new AjaxJsonResponse();
        try {
            Integer status = this.tssCourseService.updateCourseByIsBlockUp(targetDateId, isBlockUp);
            if (status == null) {
                ajr.setResMsg("修改失败!");
                ajr.setResCode(302);
            } else {
                ajr.setResMsg("修改成功!");
                ajr.setResCode(200);
            }
        } catch (Exception e) {
            e.printStackTrace();
            ajr.setResCode(500);
            ajr.setResMsg("修改失败(" + e.getMessage() + ")!");
        }
        return ajr.jsonResponse(true);

    }


    /**
     * 基础设置>员工设置模块导出 未完成
     * 杨然
     * 2017年11月9日16:57:49
     * */
    /*@RequestLog(content = "导出", save = true)
    @Token(validateToken = false)
	@ResponseBody
	@RequestMapping("/exportExcle")
	public void exportExcle(Integer flag, String ids, HttpServletResponse response, HttpServletRequest request){
		System.out.println(ids);
		String path = "jso/export_staff.json";
		List<SysAdminUser> staffList = null;

		if(ids == ""){
			//staffList = empSysAdminUserService.getAllList();
		} else {
			//staffList = empSysAdminUserService.findListByIds(Arrays.asList(ids.split(",")));
		}



	}*/

    /**
     * 根据课程体系分组查询课程信息
     *
     * @return
     */
    @ResponseBody
    @RequestLog(content = "根据课程体系分组查询课程信息", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "queryGroupBySystemPid", method = RequestMethod.POST)
    public String queryGroupBySystemPid(@RequestParam(required = true) Integer type) {
        AjaxJsonResponse ajr = new AjaxJsonResponse();
        try {
            String ids = "";
            //获取当前登录者
            String adminUserId = super.getLoginUser().getId();

            SysAdminUser sysAdminUser = this.sysAdminUserService.get(adminUserId);
            List<String> idsList = super.getUserIdByRoleAndSchololId(sysAdminUser.getSchoolId());
            ids = StringUtils.join(idsList, "','");
            String systemPid = "";
            List<Map<String, Object>> courseGroupList = this.tssCourseService.queryListBySystemPid(systemPid, type,ids);
            ajr.setData(courseGroupList.toArray());
        } catch (Exception e) {
            e.printStackTrace();
            ajr.setResCode(500);
            ajr.setResMsg("保存失败(" + e.getMessage() + ")!");
        }
        return ajr.jsonResponse(true);
    }

    /**
     * 根据课程体系查询课程信息
     *
     * @param systemPid 查询对象
     * @return
     */
    @ResponseBody
    @RequestLog(content = "根据课程体系查询课程信息", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "queryListBySystemPid", method = RequestMethod.POST)
    public String queryListBySystemPid(@RequestParam(required = true) String systemPid, @RequestParam(required = true) Integer type) {
        AjaxJsonResponse ajr = new AjaxJsonResponse();
        try {
            //获取当前登录者
            String adminUserId = super.getLoginUser().getId();
            SysAdminUser sysAdminUser = this.sysAdminUserService.get(adminUserId);
            List<String> idsList = super.getUserIdByRoleAndSchololId(sysAdminUser.getSchoolId());
            String ids = StringUtils.join(idsList, "','");

            List<Map<String, Object>> courseList = this.tssCourseService.queryListBySystemPid(systemPid, type,ids);
            ajr.setData(courseList.toArray());
        } catch (Exception e) {
            e.printStackTrace();
            ajr.setResCode(500);
            ajr.setResMsg("保存失败(" + e.getMessage() + ")!");
        }
        return ajr.jsonResponse(true);
    }


    /**
     * 验证课程名称不可重复
     *
     * @param systemId 课程
     * @return
     */
    @ResponseBody
    @RequestLog(content = "验证课程名称不可重复", save = true)
    @RequestMapping(value = "verificationCourseName", method = RequestMethod.POST)
    public String verificationCourseName(String systemId,String id) {
        try {
            StringBuffer sql = new StringBuffer();
            sql.append("select COUNT(1) count from tss_course tc left join sys_admin_user sau on sau.id=tc.adminUserId \n" +
                    "where sau.schoolId=? and tc.`systemId`=?");
            if (id != null && id != "") {
                sql.append(" AND tc.id != '" + id + "'");
            }
            String schoolId=super.getLoginUser().getSchoolId();
            Map<String, Object> findOneForJdbc = sysAdminUserService.findOneForJdbc(sql.toString(), new Object[]{super.getLoginUser().getSchoolId(),systemId});
            return responseRemoteValidate(findOneForJdbc != null && !findOneForJdbc.isEmpty() && findOneForJdbc.containsKey("count") && (findOneForJdbc.get("count").toString()).equals("0"));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
